<template>
  <div class="rental-space-management">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-indicator">数据加载中...</div>
    <div v-if="error" class="error-message">{{ error }}</div>

    <!-- 面积统计区域 -->
    <div class="top-stats">
      <div class="stat-item">
        <h4>总面积</h4>
        <p>{{ areaStats.totalArea.toFixed(2) }} m²</p>
      </div>
      <div class="stat-item">
        <h4>已租赁面积</h4>
        <p>{{ areaStats.rentedArea.toFixed(2) }} m²</p>
      </div>
      <div class="stat-item">
        <h4>闲置面积</h4>
        <p>{{ areaStats.vacantArea.toFixed(2) }} m²</p>
      </div>
      <div class="stat-item">
        <h4>维修中面积</h4>
        <p>{{ areaStats.maintenanceArea.toFixed(2) }} m²</p>
      </div>
    </div>
    <!-- 状态颜色图例 -->
    <div class="status-legend">
      <div class="legend-item vacant">
        <span class="color-box"></span> 空闲
      </div>
      <div class="legend-item rented">
        <span class="color-box"></span> 已租赁
      </div>
      <div class="legend-item maintenance">
        <span class="color-box"></span> 维修中
      </div>
    </div>

    <!-- 筛选功能 -->
    <div class="filters">
      <label>租赁状态：</label>
      <select v-model="filters.status" class="filter-input">
        <option value="all">全部</option>
        <option value="1">已租赁</option>
        <option value="0">空闲</option>
        <option value="2">维修中</option>
      </select>
      <label>租金范围：</label>
      <input type="number" v-model="filters.minRent" placeholder="最低" class="filter-input" />
      <span>-</span>
      <input type="number" v-model="filters.maxRent" placeholder="最高" class="filter-input" />
      <button @click="fetchSpacesWithFilters" class="filter-button">应用筛选</button>
      <button @click="resetFilters" class="filter-button">重置</button>
    </div>

    <!-- 空间展示区域 -->
    <div class="space-grid">
      <div v-for="space in spaces" :key="space.unitId" :class="['space-item', getStatusClass(space.status)]"
        @click="showSpaceDetails(space)">
        <div class="space-info">
          <h3>{{ getFullSpaceName(space) }}</h3>
          <p v-if="space.name" class="company-name">{{ space.name }}</p>
          <p>状态: {{ getStatusText(space.status) }}</p>
          <p>面积: {{ space.area }} m²</p>
          <p>租金: ￥{{ space.baseRent }}/月</p>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <div v-if="selectedSpace" class="space-details-modal">
      <div class="modal-content">
        <!-- 弹窗头部 -->
        <button @click="closeDetailsModal" class="close-btn">&times;</button>
        <h2>租赁空间详情</h2>

        <!-- 查看模式 -->
        <div v-if="!isEditing">
          <p><strong>空间编号:</strong> {{ getFullSpaceName(selectedSpace) }}</p>
          <p><strong>公司名称:</strong> {{ selectedSpace.name }}</p>
          <p><strong>租赁状态:</strong> {{ getStatusText(selectedSpace.status) }}</p>
          <p><strong>面积:</strong> {{ selectedSpace.area }} m²</p>
          <p><strong>租赁起始日期:</strong> {{ selectedSpace.startDate ? formatDate(selectedSpace.startDate) : '未设置' }}</p>
          <p><strong>租赁到期日期:</strong> {{ selectedSpace.endDate ? formatDate(selectedSpace.endDate) : '未设置' }}</p>
          <p><strong>租金:</strong> ￥{{ selectedSpace.baseRent }}/月</p>
          <p><strong>支付方式:</strong> {{ getPaymentCycleText(selectedSpace.paymentCycle) }}</p>
          <button @click="toggleEditMode" class="edit-button">编辑</button>
        </div>

        <!-- 编辑模式 -->
        <div v-else class="edit-form">
          <div class="form-group">
            <label>公司名称:</label>
            <input v-model="selectedSpace.name" type="text" class="edit-input" />
          </div>

          <div class="form-group">
            <label>租赁状态:</label>
            <select v-model="selectedSpace.status" class="edit-input">
              <option value="0">空闲</option>
              <option value="1">已租赁</option>
              <option value="2">维修中</option>
            </select>
          </div>

          <div class="form-group">
            <label>租金金额:</label>
            <input v-model="selectedSpace.baseRent" type="number" class="edit-input" />
          </div>

          <div class="form-group">
            <label>合同编号:</label>
            <input v-model="selectedSpace.contractNumber" type="text" class="edit-input" />
          
          </div>

          <div class="form-group">
            <label>支付方式:</label>
            <select v-model="selectedSpace.paymentCycle" class="edit-input">
              <option value="1">月付</option>
              <option value="3">季付</option>
              <option value="6">半年付</option>
              <option value="12">年付</option>
            </select>
          </div>

          <div class="form-actions">
            <button @click="updateSpace" class="save-button">保存</button>
            <button @click="toggleEditMode" class="cancel-button">取消</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

// 从环境变量中获取基础地址，自动适配开发/生产环境
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

// 空间数据（将从后端获取）
const spaces = ref([])
// 大分区数据（将从后端获取）
const zones = ref([])
const isLoading = ref(false)
const error = ref(null)
const selectedSpace = ref(null)
const isEditing = ref(false)
// 获取空间详情数据（用于编辑回显）
const fetchSpaceDetails = async (unitId) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/rentplaces/units/${unitId}`)
    return response.data.data
  } catch (err) {
    error.value = '获取详情失败: ' + err.message
    return null
  }
}

// 进入编辑模式
const toggleEditMode = async () => {
  if (!isEditing.value) {
    // 进入编辑模式时，从后端获取最新数据
    isLoading.value = true
    try {
      const freshData = await fetchSpaceDetails(selectedSpace.value.unitId)
      if (freshData) {
        selectedSpace.value = freshData
      }
    } finally {
      isLoading.value = false
    }
  }
  isEditing.value = !isEditing.value
}

// 更新空间数据
const updateSpace = async () => {
  isLoading.value = true
  try {
    const payload = {
      unitId: selectedSpace.value.unitId,
      zoneId: selectedSpace.value.zoneId,
      unitName: selectedSpace.value.unitName,
      status: selectedSpace.value.status,
      area: selectedSpace.value.area,
      baseRent: selectedSpace.value.baseRent,
      
      name: selectedSpace.value.name,
      startDate: selectedSpace.value.startDate,
      endDate: selectedSpace.value.endDate,
      contractNumber: selectedSpace.value.contractNumber,
      paymentCycle: selectedSpace.value.paymentCycle
    }

    const response = await axios.put(
      `${API_BASE_URL}/api/rentplaces/units/${selectedSpace.value.unitId}`,
      payload
    )

    // 更新本地数据
    const index = spaces.value.findIndex(s => s.unitId === selectedSpace.value.unitId)
    if (index !== -1) {
      spaces.value[index] = response.data.data
    }

    toggleEditMode()
    fetchSpacesWithFilters() // 刷新列表数据
  } catch (err) {
    error.value = '更新失败: ' + (err.response?.data?.message || err.message)
  } finally {
    isLoading.value = false
  }
}

const filters = ref({
  status: 'all',
  minRent: null,
  maxRent: null
})



// 获取带筛选条件的空间数据
const fetchSpacesWithFilters = async () => {
  isLoading.value = true
  error.value = null

  try {
    // 构建查询参数
    const params = {}
    if (filters.value.status !== 'all') {
      params.status = filters.value.status
    }
    if (filters.value.minRent) {
      params.minRent = filters.value.minRent
    }
    if (filters.value.maxRent) {
      params.maxRent = filters.value.maxRent
    }

    // 同时获取空间数据和统计信息
    const [spacesRes, zonesRes, statsRes] = await Promise.all([
      axios.get(`${API_BASE_URL}/api/rentplaces/units`, { params }),
      axios.get(`${API_BASE_URL}/api/rentplaces/zones`),
      axios.get(`${API_BASE_URL}/api/rentplaces/areaStats`, { params })
    ])

    spaces.value = spacesRes.data?.data || []
    zones.value = zonesRes.data?.data || []
    areaStats.value = {
      totalArea: statsRes.data?.data?.totalArea || 0,
      rentedArea: statsRes.data?.data?.rentedArea || 0,
      vacantArea: statsRes.data?.data?.vacantArea || 0,
      maintenanceArea: statsRes.data?.data?.maintenanceArea || 0
    }
  } catch (err) {
    error.value = err.message || '获取数据失败'
    console.error('API错误:', err)
  } finally {
    isLoading.value = false
  }
}

// 获取完整空间名称（根据实际数据结构调整）
const getFullSpaceName = (space) => {
  if (!space) return '未知空间';

  // 查找对应的区域
  const zone = zones.value.find(z => z.zoneId === space.zoneId);
  const zoneName = zone ? zone.zoneName : '未知';

  return `${zoneName}-${space.unitName || '未知'}`;
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '空闲',
    1: '已租赁',
    2: '维修中'
  }
  return statusMap[status] || '未知状态'
}

// 获取支付周期文本
const getPaymentCycleText = (cycle) => {
  const cycleMap = {
    1: '月付',
    2: '双月付',
    3: '季付',
    6: '半年付',
    12: '年付'
  }
  return cycleMap[cycle] || `每${cycle}个月付`
}

// 获取状态对应的CSS类
const getStatusClass = (status) => {
  const classMap = {
    0: 'vacant',
    1: 'rented',
    2: 'maintenance'
  }
  return classMap[status] || ''
}



// 方法
const formatDate = (dateStr) => {
  if (!dateStr) return '未设置';

  try {
    // 直接使用Date解析，因为后端返回的是标准ISO格式或类似格式
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN');
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateStr; // 如果无法解析，返回原始字符串
  }
}

const showSpaceDetails = (space) => {
  selectedSpace.value = {
    ...space,
    // 确保使用正确的属性名
    unitId: space.unitId,
    zoneId: space.zoneId,
    baseRent: space.baseRent,
    paymentCycle: space.paymentCycle,
    contractNumber: space.contractNumber
  };
};




const applyFilters = () => {
  console.log(`已应用筛选，找到 ${filteredSpaces.value.length} 条结果`)
}

const resetFilters = () => {
  filters.value = {
    status: 'all',
    minRent: null,
    maxRent: null
  }
  fetchSpacesWithFilters() // 添加这行
}

const areaStats = ref({
  totalArea: 0,
  rentedArea: 0,
  vacantArea: 0,
  maintenanceArea: 0
});

const closeDetailsModal = () => {
  selectedSpace.value = null
  isEditing.value = false
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSpacesWithFilters()
})
</script>

<style scoped>
.loading-indicator {
  padding: 10px;
  background-color: #f0f9eb;
  color: #67c23a;
  text-align: center;
  margin-bottom: 15px;
  border-radius: 4px;
}

.error-message {
  padding: 10px;
  background-color: #fef0f0;
  color: #f56c6c;
  text-align: center;
  margin-bottom: 15px;
  border-radius: 4px;
}

.rental-space-management {
  padding: 20px;
  font-family: 'Arial', sans-serif;
  background-color: #f8f9fa;
  max-width: 1200px;
  margin: 0 auto;
}

.top-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 15px;
}

.stat-item {
  background-color: #ffffff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  flex: 1;
}

.stat-item h4 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #495057;
}

.stat-item p {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.filters {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filters label {
  font-size: 14px;
  color: #555;
  white-space: nowrap;
}

.filter-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  width: 100px;
}

.filter-button {
  background-color: #409eff;
  color: white;
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.filter-button:hover {
  background-color: #66b1ff;
}

.space-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 15px;
}

.space-item {
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.space-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.space-item.vacant {
  border-left: 4px solid #67c23a;
}

.space-item.rented {
  border-left: 4px solid #e6a23c;
}

.space-item.maintenance {
  border-left: 4px solid #f56c6c;
}

.space-info h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.space-info p {
  margin: 5px 0;
  font-size: 13px;
  color: #666;
}

.space-details-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 25px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 24px;
  color: #999;
  background: none;
  border: none;
  cursor: pointer;
  padding: 5px;
}

.close-btn:hover {
  color: #333;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

.modal-content p {
  margin: 10px 0;
  font-size: 14px;
}

.edit-form {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #555;
}

.edit-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.edit-button,
.save-button,
.cancel-button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.edit-button {
  background-color: #409eff;
  color: white;
}

.save-button {
  background-color: #67c23a;
  color: white;
}

.cancel-button {
  background-color: #f56c6c;
  color: white;
}

.edit-button:hover {
  background-color: #66b1ff;
}

.save-button:hover {
  background-color: #85ce61;
}

.cancel-button:hover {
  background-color: #f78989;
}

.status-legend {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 10px;
  background: #fff;
  padding: 10px 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #333;
}

.color-box {
  width: 16px;
  height: 16px;
  border-radius: 3px;
}

/* 使用与空间卡片一致的颜色 */
.legend-item.vacant .color-box {
  background-color: #67c23a;
}

.legend-item.rented .color-box {
  background-color: #e6a23c;
}

.legend-item.maintenance .color-box {
  background-color: #f56c6c;
}

</style>